<template>
  <div id="login">
    <div style="text-align: center">
      <h2>登录</h2>
    </div>
    <a-form
      id="components-form-demo-normal-login"
      :form="form"
      class="login-form"
      @submit="handleSubmit"
    >
      <a-form-item>
        <a-input
          v-decorator="[
            'username',
            { rules: [{ required: true, message: '请输入用户名!' }] },
          ]"
          placeholder="用户名"
        >
          <a-icon slot="prefix" type="user" style="color: rgba(0, 0, 0, 0.25)" />
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-input
          v-decorator="[
            'password',
            { rules: [{ required: true, message: '请输入密码！' }] },
          ]"
          type="password"
          placeholder="密码"
        >
          <a-icon slot="prefix" type="lock" style="color: rgba(0, 0, 0, 0.25)" />
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-checkbox
          v-decorator="[
            'remember',
            {
              valuePropName: 'checked',
              initialValue: true,
            },
          ]"
        >
          记住我
        </a-checkbox>
        <a class="login-form-forgot" href="">忘记密码 </a>
        <a-button type="primary" html-type="submit" class="login-form-button">
          登录
        </a-button>
        <a href="" @click="goRegister"> 注册</a>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import jwt from "jwt-decode";
export default {
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: "normal_login" });
  },
  methods: {
    goRegister(e) {
      e.preventDefault();
      this.$router.push("/register");
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          this.$axios.post("/user/login", { ...values }).then((res) => {
            if (res.data.error === -1) {
              const decode = jwt(res.data.data.token);
              localStorage.setItem("LoginToken", res.data.data.token);
              this.$store.dispatch("setUser", decode);
              this.$store.dispatch("setToken", this.isEmpty(decode));
              this.$router.push("/blog");
            }
          });
        }
      });
    },
    isEmpty(value) {
      if (
        value == "" ||
        Object.values(value).length == 0 ||
        value == undefined ||
        Object.keys(value).length == 0
      ) {
        return false;
      } else {
        return true;
      }
    },
  },
};
</script>
<style lang="less" scoped>
#login {
  width: 400px;
  height: 300px;
  position: absolute;
  left: 0;
  top: 0;
  bottom: 30px;
  right: 0;
  margin: auto;
  text-align: left;
}
#components-form-demo-normal-login .login-form {
  max-width: 300px;
}
#components-form-demo-normal-login .login-form-forgot {
  float: right;
}
#components-form-demo-normal-login .login-form-button {
  width: 100%;
}
</style>
